package com.web;

import com.domain.Employee;
import com.service.employeeService;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.PrintWriter;

/**
 * 员工的注册
 * 接收 registEmployee.jsp 页面的表单数据，一个个接收，封装成Employee对象
 * 提交到 employeeService 的 regist 函数，
 * 转发到/loginEmployee.jsp页面，进行重新登录
 */
@WebServlet("/registEmployee")
public class RegistEmployeeServlet extends HttpServlet {
    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        System.out.println("员工在注册");

        //1.解决乱码
        request.setCharacterEncoding("utf-8");
        response.setContentType("text/html;charset=UTF-8");

        //2.接受参数
        String employeeId = request.getParameter("id");
        String username = request.getParameter("name");
        String password = request.getParameter("password");
        String phone = request.getParameter("phone");
        String address = request.getParameter("address");
        String grade = request.getParameter("grade");
        String department = request.getParameter("department");

        //3.封装对象
        Employee employee = new Employee(Integer.valueOf(employeeId),username,password,phone,address,grade,department);

        //4.将数据存储到数据库里面，调用service层
        employeeService employeeService = new employeeService();
        Integer flag = employeeService.regist(employee);

        //5.判断是否成功
        PrintWriter out = response.getWriter();
        if(flag ==0){
            //用户名重复
            out.write("注册失败, 请检查注册信息！");
            System.out.println("员工"+employeeId+"注册失败");
        }else {
            //注册成功
            response.sendRedirect(request.getContextPath()+"/loginEmployee.jsp");//重定向
            System.out.println("员工"+employeeId+"注册成功");
        }

    }

    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        doPost(request,response);
    }
}
